package cn.bisoft.java.util.os;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileUtil
{
    public static void writeFile(String fileName, byte[] data)
    {
        File file = new File(fileName);
        FileOutputStream fos = null;

        if (!file.exists())
        {
            file.mkdirs();
        }

        if (!file.isDirectory())
        {
            try
            {
                fos = new FileOutputStream(file);

                fos.write(data);

                fos.flush();
            }
            catch (FileNotFoundException e)
            {
                e.printStackTrace();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            finally
            {
                if (null != fos)
                {
                    try
                    {
                        fos.close();
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }

            }
        }
    }

    public static byte[] readFile(String fileName)
    {
        File file = new File(fileName);
        byte[] data = new byte[(int) file.getTotalSpace()];

        FileInputStream fis = null;

        try
        {
            fis = new FileInputStream(fileName);
            fis.read(data);
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        return data;

    }

    public static void mkfiles(String fileName)
    {
        String dir = FileUtil.getParentPath(fileName);

        File folder = new File(dir);
        File file = new File(fileName);

        if (!file.exists())
        {
            folder.mkdirs();
            try
            {
                file.createNewFile();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    public static String getParentPath(String fileName)
    {
        int splitIndex = fileName.lastIndexOf("/");

        if (fileName.lastIndexOf("/") == -1)
        {
            splitIndex = fileName.lastIndexOf('\\');
        }
        String dir = fileName.substring(0, splitIndex + 1);

        return dir;
    }

}
